package com.pqj.pqaiagent.tool;

import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 终端操作工具
 */
public class TerminalOperationTool {

    @Tool(description = "Execute a command in the terminal") // 标记为工具方法，描述为"在终端执行命令"
    public String executeTerminalCommand(@ToolParam(description = "Command to execute in the terminal") String command) {  // 参数：要在终端执行的命令
        StringBuilder output = new StringBuilder(); // 创建StringBuilder对象用于收集命令输出结果
        try {
            // 创建ProcessBuilder对象，用于执行Windows命令(cmd.exe)
            ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c", command);
          // 注释掉的原始执行方式：直接使用Runtime执行命令
//            Process process = Runtime.getRuntime().exec(command);
            Process process = builder.start();
            // 使用try-with-resources自动关闭资源
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {  // 创建缓冲读取器读取命令输出
                String line;
                while ((line = reader.readLine()) != null) {  // 逐行读取命令输出
                    output.append(line).append("\n");  // 将每行输出添加到结果中
                }
            }
            int exitCode = process.waitFor(); // 等待命令执行完成并获取退出码
            if (exitCode != 0) {// 如果退出码不为0表示执行失败
                output.append("Command execution failed with exit code: ").append(exitCode);
            }
        } catch (IOException | InterruptedException e) {
            output.append("Error executing command: ").append(e.getMessage());
        }
        return output.toString();
    }
}
